package com.course.masterservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.course.component.http.BasePageResponse;
import com.course.component.util.CopyUtil;
import com.course.component.util.DateUtils;
import com.course.component.util.SnowFlake;
import com.course.dto.reqs.RequestRole;
import com.course.dto.resp.ResponseRole;
import com.course.entity.Role;
import com.course.masterservice.RoleMasterService;
import com.course.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Copyright: Copyright (c)  林中小鸟  All rights reserved.
 * @author: moon
 * @date: 2022/9/20 13:48
 * @Description: **********************
 */
@Service
public class RoleMasterServiceImpl implements RoleMasterService {

    @Autowired
    private IRoleService roleService;

    @Override
    public BasePageResponse<ResponseRole> list(RequestRole requestRole) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        List<Role> list = roleService.list(queryWrapper);
        return new BasePageResponse(list.size(),list.stream().map(item-> CopyUtil.copy(item, ResponseRole.class)).collect(Collectors.toList()));
    }

    @Override
    public Boolean del(RequestRole requestRole) {
        return roleService.removeById(requestRole.getId());
    }

    @Override
    public Boolean update(RequestRole requestRole) {
        Role updateData = CopyUtil.copy(requestRole,Role.class);
        if(ObjectUtils.isEmpty(updateData.getId())){
            updateData.setId(new SnowFlake().nextId());
            updateData.setCreateTime(DateUtils.getNowDate());
        }
        return roleService.saveOrUpdate(updateData);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean linkPermission(RequestRole requestRole) {
        List<Long> ides = requestRole.getPermissionIds();
        //删除当前角色权限
        roleService.unLinkPermission(requestRole.getId().toString());
        //附加新的权限
        for(Long item : ides){
            roleService.linkPermission(requestRole.getId(),item);
        }
        return true;
    }
}
